"""
数据库初始化脚本
"""
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pymysql
from config.config import settings
from models.database import create_tables, engine
from utils.logger import app_logger

def create_database():
    """创建数据库"""
    try:
        # 连接到MySQL服务器（不指定数据库）
        connection = pymysql.connect(
            host=settings.DB_HOST,
            port=settings.DB_PORT,
            user=settings.DB_USER,
            password=settings.DB_PASSWORD,
            charset='utf8mb4'
        )
        
        cursor = connection.cursor()
        
        # 创建数据库
        cursor.execute(f"CREATE DATABASE IF NOT EXISTS {settings.DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
        print(f"✓ 数据库 '{settings.DB_NAME}' 创建成功")
        
        cursor.close()
        connection.close()
        
        return True
        
    except Exception as e:
        print(f"✗ 创建数据库失败: {str(e)}")
        return False

def create_tables_with_check():
    """创建数据库表"""
    try:
        create_tables()
        print("✓ 数据库表创建成功")
        return True
    except Exception as e:
        print(f"✗ 创建数据库表失败: {str(e)}")
        return False

def check_database_connection():
    """检查数据库连接"""
    try:
        connection = engine.connect()
        connection.close()
        print("✓ 数据库连接测试成功")
        return True
    except Exception as e:
        print(f"✗ 数据库连接测试失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("开始数据库初始化...")
    print("=" * 50)
    
    # 1. 创建数据库
    print("1. 创建数据库")
    if not create_database():
        return
    
    # 2. 测试数据库连接
    print("\n2. 测试数据库连接")
    if not check_database_connection():
        return
    
    # 3. 创建数据库表
    print("\n3. 创建数据库表")
    if not create_tables_with_check():
        return
    
    print("\n" + "=" * 50)
    print("数据库初始化完成！")
    print("\n数据库信息:")
    print(f"  主机: {settings.DB_HOST}:{settings.DB_PORT}")
    print(f"  数据库: {settings.DB_NAME}")
    print(f"  用户: {settings.DB_USER}")

if __name__ == "__main__":
    main() 